#!/bin/bash
# 兼容rocky linux 9
source /etc/profile

# 设置默认的 JDK 路径，允许通过环境变量覆盖
JAVA_HOME=${JAVA_HOME:-/opt/jdk1.7.0_80}
export JAVA_HOME
export PATH=$JAVA_HOME/bin:$PATH
export LC_ALL=zh_CN.UTF-8

usage() {
    echo "Usage: $0 -s [stop|start|restart|status] -p port"
}

# 如果没有参数，则显示用法
if [ $# -eq 0 ]; then
    usage
    exit 1
fi

# 获取传入的参数
while getopts ":s:p:" opt; do
    case $opt in
        s)
            s=$OPTARG
            if [[ "$s" != "start" && "$s" != "stop" && "$s" != "restart" && "$s" != "status" ]]; then
                echo "-s 参数错误: $s"
                usage
                exit 1
            fi
            ;;
        p)
            port=$OPTARG
            if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -gt 65535 ]; then
                echo "-p 参数错误: $port"
                usage
                exit 1
            fi
            ;;
        \?)
            echo "无效的参数: -$OPTARG"
            usage
            exit 1
            ;;
    esac
done

# 获取指定端口的 PID
pid=$(ss -ltnp | grep ":$port " | awk '{print $6}' | awk -F',' '{print $2}' | awk -F'=' '{print $2}')
binPath=$(find /home/ACS/ -type d -name 'bin' | grep $port)

if [ -z "$binPath" ]; then
    echo "未找到 bin 目录，请检查 ACS 安装路径。"
    exit 1
fi

case $s in
    restart)
        if [ -z "$pid" ]; then
            echo "ACS 进程未运行，启动 ACS $port"
            cd $binPath || { echo "无法切换到 $binPath"; exit 1; }
            nohup sh startup.sh &
            exit 0
        fi
        echo "重启 ACS $port"
        kill -9 $pid
        cd $binPath || { echo "无法切换到 $binPath"; exit 1; }
        nohup sh startup.sh &
        ;;
    start)
        echo "启动 ACS $port"
        cd $binPath || { echo "无法切换到 $binPath"; exit 1; }
        nohup sh startup.sh &
        ;;
    stop)
        if [ -z "$pid" ]; then
            echo "未找到运行的 ACS 进程，端口: $port"
            exit 0
        fi
        echo "停止 ACS $port"
        kill -9 $pid
        ;;
    status)
        if [ -z "$pid" ]; then
            echo "ACS 未在端口 $port 运行"
        else
            echo "ACS 正在端口 $port 运行，PID: $pid"
        fi
        ;;
esac